package com.zy.mc_module.view;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

import com.zy.mc_module.utils.DensityUtil;

public class RoundBackgroundColorSpan extends ReplacementSpan {
    private int bgColor;
    private int textColor;
    private int top, bottom;

    public RoundBackgroundColorSpan(int bgColor, int textColor) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
    }

    public RoundBackgroundColorSpan(int bgColor, int textColor, int top, int bottom) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
        this.top = top;
        this.bottom = bottom;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //设置宽度为文字宽度加16dp
        return ((int) paint.measureText(text, start, end) + DensityUtil.dip2px(6));
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int originalColor = paint.getColor();
        paint.setColor(this.bgColor);
        //画圆角矩形背景
        RectF rectF = new RectF(x,
                top + DensityUtil.dip2px(3) - DensityUtil.dip2px(this.top),
                x + ((int) paint.measureText(text, start, end) + DensityUtil.dip2px(6)),
                bottom - DensityUtil.dip2px(1) + DensityUtil.dip2px(this.bottom));
        canvas.drawRoundRect(rectF,
                DensityUtil.dip2px(4),
                DensityUtil.dip2px(4),
                paint);
        paint.setColor(this.textColor);
        //画文字,两边各增加8dp
        canvas.drawText(text, start, end, x + DensityUtil.dip2px(3), y, paint);
        //将paint复原
        paint.setColor(originalColor);
    }
}
